$(function () {
    initialPage();
    getGrid();
    vm.getKey();
});

function initialPage() {
    $(window).resize(function () {
        TreeGrid.table.resetHeight({height: $(window).height() - 100});
    });
}

function getGrid() {
    var colunms = TreeGrid.initColumn();
    var table = new TreeTable(TreeGrid.id, '../sys/dept/list?flag=1', colunms);
    table.setExpandColumn(2);
    table.setIdField("deptId");
    table.setCodeField("deptId");
    table.setParentCodeField("parentId");
    table.setExpandAll(true);
    table.setHeight($(window).height() - 100);
    table.init();
    TreeGrid.table = table;
}

var TreeGrid = {
    id: "sysDeptGrid",
    table: null,
    layerIndex: -1
};


/**
 * 初始化表格的列
 */
TreeGrid.initColumn = function () {
    var columns = [
        {field: 'selectItem', radio: true},
        {title: '部门ID', field: 'deptId', visible: false, align: 'center', valign: 'middle', width: '30px'},
        {title: '部门名称', field: 'name', align: 'center', valign: 'middle', sortable: true, width: '90px'},
        {title: '部门简称', field: 'shortName', align: 'center', valign: 'middle', sortable: true, width: '90px'},
        // {title: '部门类别', field: 'deptType', align: 'center', valign: 'middle', sortable: true, width: '80px'},
        {title: '部门代码', field: 'dcode', align: 'center', valign: 'middle', sortable: true, width: '50px'},
        {title: '上级部门', field: 'parentName', align: 'center', valign: 'middle', sortable: true, width: '90px'},
        {
            title: '标识',
            field: 'flag',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: '30px',
            formatter: function (value) {
                return value.flag==null?'无':sysEnums.FLAG_LIST[value.flag];
            }
        },
        {title: '车间库存前缀', field: 'posPrefix', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {title: '备件事务来源', field: 'spTxnSource', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {title: '排序号', field: 'orderNum', align: 'center', valign: 'middle', sortable: true, width: '30px'}]
    return columns;
};

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};
var ztree;

var vm = new Vue({
    el: '#sysDept',
    data: {
        showList: true,
        title: null,
        deptTypeList: [],
        flagList: enumsToList('FLAG_LIST'),//标识
        dept: {
            parentName: null,
            parentId: '01',
            orderNum: 0,
            flag: 1,
            deptType: '',
            name:'', // 部门名称
            shortName: '', // 部门简称
            dcode:'', // 部门编码
            posPrefix:''//车间库存前缀
        },
        ruleValidate: {
            name: [
                {required: true, message: '部门名称不能为空', trigger: 'blur'}
            ]
        },
        q:{
            flag:''
        }
    },

    methods: {
        getDept: function () {

            let url = "../sys/dept/select?flag=1";

            //加载部门树
            Ajax.request({
                url: url,
                async: true,
                successCallback: function (r) {

                    ztree = $.fn.zTree.init($("#sysDeptTree"), setting, r.deptList);
                    var node = ztree.getNodeByParam("deptId", vm.dept.parentId);
                    if (node) {
                        ztree.selectNode(node);
                        vm.dept.parentName = node.name;
                    } else {
                        node = ztree.getNodeByParam("deptId", '01');
                        ztree.selectNode(node);
                        vm.dept.parentName = node.name;
                    }
                }
            });
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            var deptId = TreeGrid.table.getSelectedRow();
            var parentId = '01';
            if (deptId.length != 0) {
                parentId = deptId[0].id;
            }

            //当部门为二级部门时,添加类别选择
            var deptType;
            console.log(deptId);
            if (parentId != '01') {
                //根据当前的部门id  查询部门类型
                Ajax.request({
                    url: '../sys/dept/getDeptType/' + deptId[0].id,
                    type: "POST",
                    async: false,
                    successCallback: function (r) {
                        console.log(r)
                        vm.dept.deptType = r.deptType;
                        deptType = r.deptType;
                        console.log(deptType)
                    }
                })
                vm.dept = {dcode:'',name:'',shortName: '', parentName: null, parentId: parentId,flag:1, orderNum: 0, deptType: deptType};
            } else {
                vm.getKey();
                vm.dept = {dcode:'',name:'',shortName: '',parentName: null, parentId: parentId, orderNum: 0};
            }
            vm.getDept();
        },
        update: function () {
            vm.getKey();
            var deptId = getDeptId();
            if (deptId == null) {
                return;
            }
            Ajax.request({
                url: "../sys/dept/info/" + deptId,
                async: true,
                successCallback: function (r) {
                    vm.showList = false;
                    vm.title = "修改";
                    vm.dept = r.dept;

                    vm.getDept();
                }
            });
        },
        del: function () {
            var deptId = getDeptId();
            if (!deptId) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../sys/dept/delete",
                    params: {"deptId": deptId},
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        saveOrUpdate: function (event) {
            console.log(vm.dept);
            var url = vm.dept.deptId == null ? "../sys/dept/save" : "../sys/dept/update";
            Ajax.request({
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.dept),
                type: 'POST',
                successCallback: function () {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        deptTree: function () {
            openWindow({
                title: "选择部门",
                area: ['300px', '450px'],
                content: jQuery("#sysDeptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级部门
                    vm.dept.parentId = node[0].deptId;
                    vm.dept.parentName = node[0].name;
                    console.log(node[0].parentId);
                    if (node[0].parentId == '01') {
                        vm.dept.deptType = node[0].deptType;
                    }
                    layer.close(index);
                }
            });
        },
        query: function () {
            vm.reload();
        },
        reload: function () {
            vm.getDept();
            vm.showList = true;
            TreeGrid.table.refresh();
        },
        reloadSearch: function () {
            vm.q = {
                flag: ''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        getKey: function () {
            Ajax.request({
                url: "../sys/dict/listDictItemByCode?dictCode=DEPT_TYPE",
                type: 'GET',
                async: false,
                successCallback: function (r) {
                    vm.deptTypeList = r.list;
                }
            })
        }
    }
});

function getDeptId() {
    var selected = $('#sysDeptGrid').bootstrapTreeTable('getSelections');
    if (selected.length == 0) {
        iview.Message.error("请选择一条记录");
        return ;
    } else {
        return selected[0].id;
    }
}
